package com.yixun.tkmapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by Administrator on 2017/10/16.
 */
public class InsertListSelectiveMapperUtil {

    private static final Logger log = LoggerFactory.getLogger(InsertListSelectiveMapperUtil.class);

    private static final int  BATCH_ADD_MAX_PARAM = 2000;
    /**
     * 如果有uuid的数据，就需要自己去创造
     * @param baseMapper 如果是estate,使用EstateMapper
     * @param list 批量的数据
     * @param <T> 实体
     */
    public static  <T>  int insertListSelective(BaseMapper  baseMapper,List<T> list){
        //对象的几个属性
        if(list == null || list.size() == 0){
            throw new RuntimeException("list is not null");
        }
        Class entityClass =  list.get(0).getClass();
        //反射获取所有列
        //计算对象排除id的所有属性，包含父类的属性 3 ，4  算出size 2000/3 list;
        //设置uuid问题
        Class clazz = entityClass;
        int count = 0;
        for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
            try {
                count+= clazz.getDeclaredFields().length;
            } catch (Exception e) {
                //这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                //如果这里的异常打印或者往外抛，则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        log.info("count==="+count);
        Integer listSize = list.size();
        Integer pageSize =  BATCH_ADD_MAX_PARAM /(count-1);//一批有多少数据，刚好取整数
        Integer pageTotal = (listSize - 1) / pageSize + 1;
        List<T> pageList;
        int resultCount =0;
        try{
            for (int i = 1; i <= pageTotal; i++) {
                if (i < (pageTotal)) {
                    pageList = list.subList((i - 1) * pageSize, i * pageSize);
                } else {
                    pageList = list.subList((i - 1) * pageSize, listSize);
                }
                if(!pageList.isEmpty() ){
                    resultCount +=baseMapper.insertList(pageList);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultCount;
    }

}
